package com.data.hijack.service;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import org.apache.log4j.Logger;

import com.data.hijack.util.BeanUtils;

/**
 * 
 * @author husq
 */
public class ReceivedHandler implements Handler {
    private static final Logger logger = Logger.getLogger(ReceivedHandler.class);
    private ServerSocketChannel serverSocketChannel;
    private String bizName;

    public ReceivedHandler(ServerSocketChannel serverSocketChannel, String bizName) {
        this.serverSocketChannel = serverSocketChannel;
        this.bizName = bizName;
    }

    @Override
    public Runnable handle() {
        SocketChannel socketChannel = null;
        try {
            socketChannel = serverSocketChannel.accept();
        } catch (IOException e) {
            logger.error(e);
        }

        if (socketChannel != null) {
            return this.getRunnable(socketChannel);
        }

        return null;
    }

    private Runnable getRunnable(SocketChannel channel) {
        try {
            return (Runnable)BeanUtils.instantiateClass(
                MessageHandler.class.getDeclaredConstructor(SocketChannel.class, Integer.TYPE, String.class),
                new Object[] {channel, SelectionKey.OP_READ, bizName});
        } catch (NoSuchMethodException e) {
            new RuntimeException(e);
        }

        return null;
    }
}
